home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 25 / Cream of the Crop 25.iso / faq / wdj0497.zip / HEAPOLE.ZIP / ALLOC.CPP < prev    next >
C/C++ Source or Header  |  1997-02-03  |  2KB  |  95 lines

  1. #include <assert.h>
  2. #include "alloc.h"
  3.  
  4. #if defined(__BORLANDC__)
  5. #   pragma argsused
  6. #endif
  7. void    DummyFree(void* Foo)
  8.     {
  9.     }
  10.  
  11. #if defined(__BORLANDC__)
  12. #   pragma argsused
  13. #endif
  14. void*   DummyMalloc(size_t Size)
  15.     {
  16.     return 0;
  17.     }
  18.  
  19. HANDLE      MyHeap;
  20. IMalloc*    OleAlloc;
  21.  
  22.  
  23. int     AllocInit(void)
  24.     {
  25.     MyHeap  = HeapCreate(HEAP_NO_SERIALIZE, 1024, 0);
  26.     assert(MyHeap != NULL);
  27.     CoGetMalloc(1, &OleAlloc);
  28.     assert(OleAlloc != NULL);
  29.     return TRUE;
  30.     }
  31.  
  32.  
  33. void*  GetMem(DWORD n)    {
  34.     return VirtualAlloc(0, n, MEM_RESERVE,
  35.         PAGE_READWRITE);
  36.     }
  37. static void    FreeMem(LPVOID P)
  38.     {  assert(VirtualFree(P, 0, MEM_RELEASE) != FALSE);  }
  39.  
  40. /* figure out how much memory is available */
  41. DWORD    MemAvail()
  42.     {
  43.     int     i       = 0;
  44.     DWORD   Avail   = 0;
  45.     DWORD   Size    = 4096*0x40000;
  46.     LPVOID  Ptrs[4096];
  47.     
  48.     memset(Ptrs, 0, sizeof(Ptrs));
  49.  
  50.     while(Size >= 4096)
  51.         {
  52.         while((Ptrs[i] = GetMem(Size)) != 0)
  53.             {
  54.             Avail   += Size;
  55.             ++i;
  56.             assert(i < 4095);
  57.             }
  58.         Size    /= 2;
  59.         }
  60.  
  61.     for(i = 0; Ptrs[i]; ++i)
  62.         FreeMem(Ptrs[i]);
  63.  
  64.     return Avail;
  65.     }
  66.  
  67. /* figure out how much memory is available */
  68. DWORD    MemStats(DWORD* PCommitted)
  69.     {
  70.     MEMORY_BASIC_INFORMATION    Info;
  71.     DWORD                       Address     = 0;
  72.     DWORD                       MaxAddr     = 0xFFFFFFFF;
  73.     DWORD                       Reserved    = 0;
  74.     DWORD                       Committed   = 0;
  75.  
  76.     for(;;)
  77.         {
  78.         VirtualQuery((LPVOID)Address, &Info, sizeof(Info));
  79.         if(Info.State != MEM_FREE)
  80.             {
  81.             Reserved   += Info.RegionSize;
  82.             if(Info.State == MEM_COMMIT)
  83.                 Committed  += Info.RegionSize;
  84.             }
  85.         if((MaxAddr - Address) <= Info.RegionSize)
  86.             break;
  87.         else
  88.             Address += Info.RegionSize;
  89.         }
  90.     if(PCommitted)
  91.         *PCommitted = Committed;
  92.     return Reserved;
  93.     }
  94.  
  95.